<template>
  <div>
    <Heads :right-flag="false" title="优惠券"></Heads>

    <van-coupon-list
      :coupons="isCoupons"
      :chosen-coupon="chosenCoupon"
      :disabled-coupons="disabledCoupons"
      :show-close-button="false"
      input-placeholder="请输入兑换码"
      @change="onChange"
      @exchange="onExchange"
    />
  </div>
</template>

<script>
import { post } from "@/utils/axios";
import { mapMutations, mapActions, mapState } from "vuex";
import Vue from "vue";
import { CouponList, Toast } from "vant";

Vue.use(CouponList).use(Toast);
const coupon = {
  // available: 1,
  id: "优惠券 id	string",
  // 左
  condition: "满减条件 无使用门槛\n最多优惠12元",
  value: 150,
  valueDesc: "1.5",
  unitDesc: "元",
  // 右
  name: "优惠券名称",
  startAt: 1590165539.177,
  endAt: 1514592000,
  // 下方
  description: "描述信息，优惠券可用时展示	string",
  reason: "不可用原因，优惠券不可用时展示	string"
};
export default {
  data() {
    return {
      chosenCoupon: -1, // 当前选中优惠券的索引(-1上来是没选中的)
      disabledCoupons: [coupon]
    };
  },
  computed: {
    ...mapState("goodsModule", ["coupons"]),
    ...mapState("userModule", ["userinfo"]),
    isCoupons() {
      if (
        Array.isArray(this.userinfo.coupons) &&
        this.userinfo.coupons.length > 0
      ) {
        let arr = [];
        this.userinfo.coupons.forEach(item => {
          // 根据用户的优惠券从优惠券文档获取详细信息
          let obj =
            Array.isArray(this.coupons) &&
            this.coupons.length > 0 &&
            this.coupons.filter(one => one.id === item.split("#")[0]);
          if (obj.length > 0) {
            arr.push({
              ...obj[0],
              id: item
            });
          }
        });
        return arr;
      } else {
        return [];
      }
    }
  },
  methods: {
    ...mapMutations("footerModule", ["FOOTERSHOW"]),
    ...mapActions("goodsModule", ["getCouponsAction"]),
    ...mapActions("userModule", ["GETUSERINFO"]),
    onChange(index) {
      this.chosenCoupon = index;
    },
    onExchange(code) {
      post({
        url: "/hybrid/uni/add-couponse-code",
        data: {
          code
        }
      }).then(res => {
        this.GETUSERINFO();
        Toast({
          message: res.msg,
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
      });
      // this.coupons.push(coupon);
    }
  },
  mounted() {
    this.FOOTERSHOW(false);
    if (!this.coupons) {
      this.getCouponsAction();
    }
    // console.log(this.userinfo, this.coupons)
  },
  destroyed() {
    this.FOOTERSHOW(true);
    this.logintab = false;
  }
};
</script>

<style>
.van-coupon-list__empty img {
  /* 空页面 */
  margin: auto;
}
.van-checkbox__icon {
  display: none;
}
</style>